<script>
export default {
  name: 'Index'
}
</script>
<template>
  <div
    v-loading="loading"
    :element-loading-text="loadingText"
    class="flex flex-col items-center justify-center m-4"
  >
    <el-tabs model-value="baseSetting" class="demo-tabs">
      <!-- 基础配置 -->
      <el-tab-pane class="w-full" label="基础配置" name="baseSetting">
        <el-card shadow="never" class="w-full">
          <div>
            <AppForm v-model="form" :items="formItem"></AppForm>
          </div>
        </el-card>
      </el-tab-pane>
      <!-- HTTPS配置 -->
      <el-tab-pane class="w-full" label="HTTPS 配置" name="httpsSetting">
        <el-card shadow="never" class="w-full">
          <div>
            <AppForm v-model="form" :items="httpsSwitch"></AppForm>
            <AppForm v-show="form.is_https == true" v-model="form" :items="httpsItem"></AppForm>
          </div>
        </el-card>
      </el-tab-pane>
      <!-- 调用说明 -->
      <el-tab-pane class="w-full" label="调用说明" name="call">
        <el-card shadow="never" class="w-full">
          <div class="markdown-body">
            <div id="markdown-content" v-html="markdownText"></div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onActivated, onMounted, nextTick, watch } from 'vue'
import formItem from './form.json'
import httpsSwitch from './https-switch.json'
import httpsItem from './https.json'
import { ElMessage } from 'element-plus'
import { debounce } from 'lodash'
import markdownit from 'markdown-it'
import 'github-markdown-css'
import readmeMd from './README.md?raw'

import AppForm from '@renderer/components/app-form/app-form'

const loading = ref(false)
const loadingText = ref('正在启动服务...')
const form = reactive({})
const formOld = reactive({})
const serverStart = ref(form.start || false)
const serverPort = ref(form.port || 0)
const autoStart = ref(form.auto_start || false)
// MD使用说明
const md = markdownit({
  html: true,
  linkify: true,
  typographer: true
})
const markdownText = ref(md.render(readmeMd))

const onChangedTips = debounce(() => {
  ElMessage.warning('配置已修改，请重启服务')
}, 500)
// 表单提交
const onSubmit = debounce(() => {
  // console.log('submit!', form)
  app
    .setConfig(JSON.stringify(form), 'img-server')
    .then(afterConfigModify)
    .catch((err) => {
      console.log('setConfig', err)
      ElMessage.error('保存失败')
    })
}, 500)

async function startServer() {
  await app
    .startServer()
    .then((res) => {
      if (res.code == 200) {
        ElMessage.success(res?.msg || '服务已启动')
      } else {
        ElMessage.error(res?.msg || '服务启动失败')
        form.start = false
      }
    })
    .catch((err) => {
      ElMessage.error(err?.msg || '服务启动失败')
      form.start = false
    })
}

async function stopServer() {
  await app
    .stopServer()
    .then((res) => {
      if (res.code == 200) {
        ElMessage.success(res?.msg || '服务已停止')
      } else {
        ElMessage.error(res?.msg || '服务停止错误')
      }
    })
    .catch((err) => {
      ElMessage.error(err?.message || '服务停止失败')
    })
}

/**
 * @Author: lcq
 * @Date: 2025-01-20 20:05:19
 * @brief: 配置修改后
 * @return {*}
 */
async function afterConfigModify() {
  if (serverStart.value != form.start) {
    serverStart.value = form.start
    if (serverStart.value) {
      await startServer()
    } else {
      await stopServer()
    }
    loading.value = false
  }
  await setAutoStart()
}
/**
 * @Author: lcq
 * @Date: 2025-01-21 16:40:46
 * @brief: 设置开机自启
 * @return {*}
 */
async function setAutoStart() {
  if (form.auto_start != autoStart.value) {
    try {
      if (form.auto_start) {
        await app.setAutoLaunch()
        ElMessage.success('服务已设置为开机自启')
      } else {
        await app.unsetAutoLaunch()
        ElMessage.success('服务已取消开机自启')
      }
      autoStart.value = form.auto_start
    } catch (err) {
      console.log('autoStart err', err)
      ElMessage.error('设置开机自启失败')
    }
  }
}
/**
 * @Author: lcq
 * @Date: 2025-01-20 18:55:48
 * @brief: 获取服务设置
 * @return {*}
 */
async function getSetting() {
  await app
    .getConfig('img-server')
    .then(async (res) => {
      console.log('res', res)
      res.port = res?.port || 3000
      serverStart.value = res?.start || false
      serverPort.value = res?.port ?? 3000
      Object.assign(form, res)
      Object.assign(formOld, res)
      // 获取开机自启状态
      app
        .isAutoLaunchEnabled()
        .then((isEnabled) => {
          autoStart.value = form.auto_start = isEnabled
        })
        .catch((err) => {
          console.log('isAutoLaunchEnabled err', err)
        })
    })
    .catch((err) => {
      console.log('getConfig err', err)
    })
}
/**
 * @Author: lcq
 * @Date: 2025-01-20 21:48:21
 * @brief: 监听表单变化
 * @return {*}
 */
function watchFormChange() {
  watch(
    form,
    (newVal) => {
      nextTick(() => {
        newVal.start == true &&
          (newVal.img_path != formOld.img_path ||
            newVal.port != formOld.port ||
            newVal.is_https != formOld.is_https ||
            newVal.https_key != formOld.https_key ||
            newVal.https_cert != formOld.https_cert) &&
          onChangedTips()
        // 服务停止或启动
        if (newVal.start != formOld.start) {
          loading.value = true
          if (newVal.start) {
            loadingText.value = '正在启动服务...'
          } else {
            loadingText.value = '正在停止...这可能需要一些时间'
          }
        }
        Object.assign(formOld, newVal)
      })
      // 提交修改变动后的数据
      onSubmit()
    },
    { deep: true }
  )
}

onActivated(async () => {})

onMounted(async () => {
  await nextTick()
  // 获取配置
  await getSetting()
  // 监听变动
  watchFormChange()
  if (serverStart.value) {
    loading.value = true
    await startServer()
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
@use '@renderer/views/index/index.scss' as *;
</style>
